import React, { useState, useEffect } from 'react';
import {
  Badge,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Space,
  message,
  Popconfirm,
  Tag,
  Table,
  Card,
  Row,
  Col,
  Tooltip,
  InputNumber,
  Divider,
  Typography,
  Drawer,
  Descriptions
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  FolderOutlined,
  FileOutlined,
  ApiOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  MenuOutlined,
  LinkOutlined,
  AppstoreOutlined,
  CloseOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useMenus, useMenuTypeOptions, type MenuFormData } from '../../hooks/business/useMenus';
import { useErrorHandler } from '../../hooks/common/useErrorHandler';
import type { Menu } from '../../types/rbac';
import { getAntdIcon } from '@/services/menuService';

const { Option } = Select;
const { Search } = Input;
const { TextArea } = Input;
const { Title, Text } = Typography;

const MenusPage: React.FC = () => {
  // 使用菜单管理hooks
  const {
    menus,
    menuTree,
    searchParams,
    expandedKeys,
    setExpandedKeys,
    loading,
    fetchMenus,
    createMenu,
    updateMenu,
    deleteMenu,
    deleteMenus,
    handleSearch,
    handleReset,
    handleFilterChange,
    refresh,
  } = useMenus();

  // 使用菜单类型选项hooks
  const { MENU_TYPE_OPTIONS, STATUS_OPTIONS } = useMenuTypeOptions();

  // 使用错误处理hooks
  const { handleError } = useErrorHandler();

  // 本地UI状态
  const [modalVisible, setModalVisible] = useState(false);
  const [editingMenu, setEditingMenu] = useState<Menu | null>(null);
  const [form] = Form.useForm<MenuFormData>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  
  // 侧边栏状态
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [viewingMenu, setViewingMenu] = useState<Menu | null>(null);

  // 初始化数据
  useEffect(() => {
    fetchMenus();
  }, []); // 移除fetchMenus依赖，只在组件挂载时执行一次

  // 搜索处理
  const handleSearchChange = (value: string) => {
    handleSearch(value);
  };

  // 处理筛选条件变化
  const handleTypeFilterChange = (value: any) => {
    handleFilterChange('type', value);
  };

  // 打开新增/编辑弹框
  const handleOpenModal = (menu?: Menu) => {
    setEditingMenu(menu || null);
    setModalVisible(true);
    
    // 使用 setTimeout 确保 Modal 完全打开后再设置表单值
    setTimeout(() => {
      if (menu) {
        // 处理permissions字段，将数组转换为字符串
        const permissions = Array.isArray(menu.permissions) 
          ? menu.permissions.join(',') 
          : menu.permissions || '';
        
        // 确保type字段为数字类型
        const type = typeof menu.type === 'number' ? menu.type : 
                     menu.type === 'menu' ? 2 : 
                     menu.type === 'button' ? 3 : 1;
        
        // 确保status字段为数字类型
        const status = typeof menu.status === 'number' ? menu.status :
                       menu.status === 'active' ? 1 : 0;
        
        // 设置表单值
        form.setFieldsValue({
          id: menu.id,
          code: menu.code || '',
          name: menu.name || '',
          permissions: permissions,
          parentId: menu.parentId || undefined,
          type: type,
          icon: menu.icon || undefined,
          path: menu.path || '',
          status: status,
          sort: menu.sort !== undefined ? menu.sort : 0,
          description: menu.description || ''
        });
      } else {
        // 新增时重置表单并设置默认值
        form.resetFields();
        form.setFieldsValue({
          type: 2,
          status: 1,
          sort: 0
        });
      }
    }, 100);
  };

  // 关闭弹框
  const handleCloseModal = () => {
    setModalVisible(false);
    setEditingMenu(null);
    form.resetFields();
  };

  // 打开查看侧边栏
  const handleViewMenu = (menu: Menu) => {
    setViewingMenu(menu);
    setDrawerVisible(true);
  };

  // 关闭查看侧边栏
  const handleCloseDrawer = () => {
    setDrawerVisible(false);
    setViewingMenu(null);
  };

  // 保存菜单
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingMenu) {
        // 编辑菜单
        const updateData = {
          id: editingMenu.id,
          ...values
        };
        await updateMenu(updateData);
      } else {
        // 新增菜单
        await createMenu(values);
      }
      
      handleCloseModal();
    } catch (error: any) {
      // 处理表单验证错误
      if (error?.errorFields) {
        message.error('请检查表单输入');
        return;
      }
      
      // 其他错误由hooks统一处理
      handleError(error);
    }
  };

  // 删除菜单
  const handleDelete = async (id: string) => {
    try {
      await deleteMenu(id);
    } catch (error: any) {
      handleError(error);
    }
  };

  // 批量删除菜单
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的菜单');
      return;
    }
    
    try {
      await deleteMenus(selectedRowKeys as string[]);
      setSelectedRowKeys([]);
    } catch (error: any) {
      handleError(error);
    }
  };

  // 获取菜单类型显示
  const getMenuTypeDisplay = (type: number | string) => {
    const typeNum = typeof type === 'number' ? type : 
                    type === 'menu' ? 2 : 
                    type === 'button' ? 3 : 1;
    
    const option = MENU_TYPE_OPTIONS.find(opt => opt.value === typeNum);
    return option ? (
      <Space>
        {option.icon}
        <span>{option.label}</span>
      </Space>
    ) : type;
  };

  // 获取状态显示
  const getStatusDisplay = (status: number | string) => {
    const statusNum = typeof status === 'number' ? status :
                      status === 'active' ? 1 : 0;
    
    const option = STATUS_OPTIONS.find(opt => opt.value === statusNum);
    return option ? (
      <Badge status={option.color as any} text={option.label} />
    ) : status;
  };

  // 表格列定义
  const columns: ColumnsType<Menu> = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
      width: 300,
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: '菜单编码',
      dataIndex: 'code',
      key: 'code',
      width: 150,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: getMenuTypeDisplay,
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
      width: 300,
      render: (text: string) => text ? <Text code>{text}</Text> : '-',
    },
    {
      title: '权限标识',
      dataIndex: 'permissions',
      key: 'permissions',
      width: 200,
      render: (permissions: string | string[]) => {
        if (!permissions) return '-';
        
        const permArray = Array.isArray(permissions) ? permissions : [permissions];
        return (
          <div>
            {permArray.map((perm, index) => (
              <Tag key={index} color="blue" style={{ marginBottom: 2 }}>
                {perm}
              </Tag>
            ))}
          </div>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: getStatusDisplay,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
      sorter: (a, b) => (a.sort || 0) - (b.sort || 0),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewMenu(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleOpenModal(record)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确定要删除这个菜单吗？"
              description="删除后不可恢复，请谨慎操作"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="link"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
    getCheckboxProps: (record: Menu) => ({
      disabled: record.children && record.children.length > 0, // 有子菜单的不能选择
    }),
  };

  return (
    <>
      {/* 页面标题 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <Title level={4} style={{ margin: 0, display: 'flex', alignItems: 'center' }}>
            <MenuOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            菜单管理
          </Title>
          <Text type="secondary">管理系统菜单结构和权限配置</Text>
        </div>
        <Space>
          <Search
            placeholder="搜索菜单名称或编码"
            allowClear
            onSearch={handleSearchChange}
            style={{ width: 300 }}
          />
          <Select
            placeholder="选择菜单类型"
            allowClear
            style={{ width: 150 }}
            onChange={handleTypeFilterChange}
            value={searchParams.type}
          >
            {MENU_TYPE_OPTIONS.map(option => (
              <Option key={option.value} value={option.value}>
                <Space>
                  {option.icon}
                  {option.label}
                </Space>
              </Option>
            ))}
          </Select>
          <Button
            icon={<ReloadOutlined />}
            onClick={refresh}
          >
            刷新
          </Button>
          <Button
            icon={<SearchOutlined />}
            onClick={handleReset}
          >
            重置
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={handleBatchDelete}
            disabled={selectedRowKeys.length === 0}
          >
            批量删除
          </Button>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => handleOpenModal()}
          >
            新增菜单
          </Button>
        </Space>
      </div>

      <Card>

        {/* 菜单表格 */}
        <Table
          columns={columns}
          dataSource={menuTree}
          rowKey="id"
          loading={loading}
          pagination={false}
          rowSelection={rowSelection}
          expandable={{
            expandedRowKeys: expandedKeys,
            onExpandedRowsChange: (keys) => setExpandedKeys(Array.from(keys)),
            defaultExpandAllRows: false,
          }}
          scroll={{ x: 1200 }}
          size="middle"
        />
      </Card>

      {/* 新增/编辑菜单弹框 */}
      <Modal
        title={editingMenu ? '编辑菜单' : '新增菜单'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={handleCloseModal}
        width={900}
        confirmLoading={loading}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            type: 2,
            status: 1,
            sort: 0
          }}
        >
          <Row gutter={[16, 8]}>
            <Col span={8}>
              <Form.Item
                label="菜单名称"
                name="name"
                rules={[
                  { required: true, message: '请输入菜单名称' },
                  { max: 50, message: '菜单名称不能超过50个字符' }
                ]}
                style={{ marginBottom: 16 }}
              >
                <Input placeholder="请输入菜单名称" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="菜单编码"
                name="code"
                rules={[
                  { required: true, message: '请输入菜单编码' },
                  { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '编码必须以字母开头，只能包含字母、数字和下划线' }
                ]}
                style={{ marginBottom: 16 }}
              >
                <Input placeholder="请输入菜单编码" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="菜单类型"
                name="type"
                rules={[{ required: true, message: '请选择菜单类型' }]}
                style={{ marginBottom: 16 }}
              >
                <Select placeholder="请选择菜单类型">
                  {MENU_TYPE_OPTIONS.map(option => (
                    <Option key={option.value} value={option.value}>
                      <Space>
                        {option.icon}
                        {option.label}
                      </Space>
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={[16, 8]}>
            <Col span={8}>
              <Form.Item
                label="上级菜单"
                name="parentId"
                style={{ marginBottom: 16 }}
              >
                <Select
                  placeholder="请选择上级菜单"
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                     !!option?.label?.toString().toLowerCase().includes(input.toLowerCase())
                   }
                >
                  {menus
                    .filter(menu => menu.type !== 3) // 排除按钮类型
                    .map(menu => (
                      <Option key={menu.id} value={menu.id}>
                        {menu.name}
                      </Option>
                    ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="菜单图标"
                name="icon"
                style={{ marginBottom: 16 }}
              >
                <Input placeholder="请输入图标名称" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="菜单路径"
                name="path"
                style={{ marginBottom: 16 }}
              >
                <Input placeholder="请输入菜单路径" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={[16, 8]}>
            <Col span={8}>
              <Form.Item
                label="状态"
                name="status"
                rules={[{ required: true, message: '请选择状态' }]}
                style={{ marginBottom: 16 }}
              >
                <Select placeholder="请选择状态">
                  {STATUS_OPTIONS.map(option => (
                    <Option key={option.value} value={option.value}>
                      <Badge status={option.color as any} text={option.label} />
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="排序"
                name="sort"
                style={{ marginBottom: 16 }}
              >
                <InputNumber
                  placeholder="请输入排序值"
                  min={0}
                  max={9999}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              {/* 占位列，保持布局对齐 */}
            </Col>
          </Row>

          <Row gutter={[16, 8]}>
            <Col span={12}>
              <Form.Item
                label="权限标识"
                name="permissions"
                tooltip="多个权限用逗号分隔，如：user:read,user:write"
                style={{ marginBottom: 16 }}
              >
                <TextArea
                  placeholder="请输入权限标识，多个权限用逗号分隔"
                  rows={2}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="描述"
                name="description"
                style={{ marginBottom: 16 }}
              >
                <TextArea
                  placeholder="请输入菜单描述"
                  rows={2}
                  maxLength={200}
                  showCount
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
        </Modal>

        {/* 查看菜单详情侧边栏 */}
        <Drawer
          title={
            <Space>
              <EyeOutlined />
              <span>菜单详情</span>
            </Space>
          }
          placement="right"
          width={600}
          open={drawerVisible}
          onClose={handleCloseDrawer}
          extra={
            <Button
              type="text"
              icon={<CloseOutlined />}
              onClick={handleCloseDrawer}
            />
          }
        >
          {viewingMenu && (
            <div>
              <Descriptions
                title="基本信息"
                bordered
                column={1}
                size="small"
                style={{ marginBottom: 24 }}
              >
                <Descriptions.Item label="菜单名称">
                  <Space>
                    <span style={{ fontWeight: 500 }}>{viewingMenu.name}</span>
                  </Space>
                </Descriptions.Item>
                <Descriptions.Item label="菜单编码">
                  <Text code>{viewingMenu.code}</Text>
                </Descriptions.Item>
                <Descriptions.Item label="菜单类型">
                  {getMenuTypeDisplay(viewingMenu.type)}
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  {getStatusDisplay(viewingMenu.status)}
                </Descriptions.Item>
                <Descriptions.Item label="排序">
                  <Text>{viewingMenu.sort || 0}</Text>
                </Descriptions.Item>
              </Descriptions>

              <Descriptions
                title="路径与权限"
                bordered
                column={1}
                size="small"
                style={{ marginBottom: 24 }}
              >
                <Descriptions.Item label="菜单路径">
                  {viewingMenu.path ? (
                    <Text code copyable>{viewingMenu.path}</Text>
                  ) : (
                    <Text type="secondary">-</Text>
                  )}
                </Descriptions.Item>
                <Descriptions.Item label="权限标识">
                  {viewingMenu.permissions ? (
                    <div>
                      {(Array.isArray(viewingMenu.permissions) 
                        ? viewingMenu.permissions 
                        : [viewingMenu.permissions]
                      ).map((perm, index) => (
                        <Tag key={index} color="blue" style={{ marginBottom: 4 }}>
                          {perm}
                        </Tag>
                      ))}
                    </div>
                  ) : (
                    <Text type="secondary">-</Text>
                  )}
                </Descriptions.Item>
              </Descriptions>

              <Descriptions
                title="层级关系"
                bordered
                column={1}
                size="small"
                style={{ marginBottom: 24 }}
              >
                <Descriptions.Item label="上级菜单">
                  {viewingMenu.parentId ? (
                    (() => {
                      const parentMenu = menus.find(m => m.id === viewingMenu.parentId);
                      return parentMenu ? (
                        <Space>
                          {parentMenu.icon && <span className="anticon">{parentMenu.icon}</span>}
                          <span>{parentMenu.name}</span>
                          <Text type="secondary">({parentMenu.code})</Text>
                        </Space>
                      ) : (
                        <Text type="secondary">未找到上级菜单</Text>
                      );
                    })()
                  ) : (
                    <Text type="secondary">顶级菜单</Text>
                  )}
                </Descriptions.Item>
                <Descriptions.Item label="子菜单数量">
                  <Badge 
                    count={viewingMenu.children?.length || 0} 
                    showZero 
                    color="blue"
                  />
                </Descriptions.Item>
              </Descriptions>

              {viewingMenu.description && (
                <Descriptions
                  title="描述信息"
                  bordered
                  column={1}
                  size="small"
                  style={{ marginBottom: 24 }}
                >
                  <Descriptions.Item label="描述">
                    <Text>{viewingMenu.description}</Text>
                  </Descriptions.Item>
                </Descriptions>
              )}

              <Descriptions
                title="系统信息"
                bordered
                column={1}
                size="small"
              >
                <Descriptions.Item label="菜单ID">
                  <Text code>{viewingMenu.id}</Text>
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  <Text>
                    {viewingMenu.createTime 
                      ? new Date(viewingMenu.createTime).toLocaleString()
                      : '-'
                    }
                  </Text>
                </Descriptions.Item>
                <Descriptions.Item label="更新时间">
                  <Text>
                    {viewingMenu.updateTime 
                      ? new Date(viewingMenu.updateTime).toLocaleString()
                      : '-'
                    }
                  </Text>
                </Descriptions.Item>
              </Descriptions>

              {/* 操作按钮 */}
              <div style={{ marginTop: 24, textAlign: 'center' }}>
                <Space>
                  <Button
                    type="primary"
                    icon={<EditOutlined />}
                    onClick={() => {
                      handleCloseDrawer();
                      handleOpenModal(viewingMenu);
                    }}
                  >
                    编辑菜单
                  </Button>
                  <Button
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => {
                      handleCloseDrawer();
                      handleDelete(viewingMenu.id);
                    }}
                  >
                    删除菜单
                  </Button>
                </Space>
              </div>
            </div>
          )}
        </Drawer>
      </>
    );
  };

  export default MenusPage;